﻿/// <reference path="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" />
/// <reference path="/knockout-2.1.0.debug.js"/>
/// <reference path="/knockout.mapping-latest.debug.js"/>

jQuery(function ($) {
    var baseServicepath = fiddleService.ServicesFramework.getServiceRoot('DNNFiddle') + 'Fiddle.ashx/';

	function pageRenderViewModel( ) {
	    var self = this;
	    self.template = '\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n    \u003chead\u003e\n        \u003cbase href=\"http://[[baseUrl]]/\" /\u003e\n        [[headtags]]    \u003c/head\u003e\n    \u003cbody\u003e\n        [[html]]        \u003cscript type=\"text/javascript\"\u003e\n        (function () { \n            [[javascript]]        })();\n        \u003c/script\u003e\n    \u003c/body\u003e\n\u003c/html\u003e';
		self.showSpinner = ko.observable( false );
		self.pageUrl = ko.observable();

		self.pageUrl.equalityComparer = function () {
			return false;
		};
		self.render = function ( headTags, htmlContent, jsContent ) {
			self.showSpinner( true );
			var page = self.template
				.replace("[[baseUrl]]", window.location.host)
				.replace("[[headtags]]", headTags || "")
				.replace("[[html]]", htmlContent)
				.replace("[[javascript]]", jsContent);
			if (!$.browser.msie) {
			    var dataPageUrl = "data:text/html;charset=utf-8," + encodeURIComponent(page);
			    self.pageUrl(dataPageUrl);
			    setTimeout(function () {
			        self.showSpinner(false)
			    }, 300)
			} else {
			    self.createTempPage(page);
			    setTimeout(function () {
			        self.showSpinner(false)
			    }, 300)
			}
		}

		self.createTempPage = function (page) {
		    var pageDTO = { "page": page };
		    $.ajax({
		        type: "POST",
		        beforeSend: fiddleService.ServicesFramework.setModuleHeaders,
		        url: baseServicepath + "CreateTempPage",
		        data: fiddleService.ServicesFramework.getAntiForgeryProperty(pageDTO),
		        dataType: "json"
		    })
            .done(function (data) {
                self.pageUrl(appModel.baseUrl + data.urlFragment);
            });
		};

	};

	function script(data) {
	    this.scriptid = data.scriptid || 0;
	    this.name = ko.observable(data.name);
	    this.url = ko.observable(data.url);
	    this.enabled = ko.observable(data.enabled);
	    this.order = ko.observable(data.order);
	    this.canDelete = ko.observable(data.canDelete);
	};

	function contentViewModel(data) {
	    var self = this;
	    ko.mapping.fromJS(data, {}, self);

	    this.removeScript = function (script) {
	        self.scripts.destroy(script);
	    };
	    this.addScript = function () {
	        self.scripts.push(new script({
	            name: "",
	            url: "",
	            enabled: false,
	            canDelete: true,
	            order: self.scripts().length
	        }));
	    };
    };

	function codeEditorViewModel(mode) {
	    var self = this;
	    self.mode = mode;
	    self.content = null;
	    self.editor = null;
	    self.updateContentFromUiFunction = ko.observable();
	    self.refresh = function () {
	        if (self.editor) self.editor.refresh();
	    };
	};

	function appViewModel( options ) {
	    var self = this;
	    var mapping = {
	        create: function (options) {
	            return new contentViewModel(options.data);
	        }
	    }

		self.previewFrame = options.iframe;
		self.windowHeight = ko.observable($(window).height());
		self.showSpinner = ko.observable(false);
		self.showSettings = ko.observable(false);
		self.fiddleHeight = ko.computed(function () {
			var iframe = $( window.parent.document )
							.find( '#iPopUp' );
			var padding = iframe.length > 0 ?
							iframe.css( 'paddingTop' )
							.replace( 'px', '' ) : 800;

			padding = parseInt( padding );

			if ( self.windowHeight() === undefined ||
			     self.windowHeight() === null ) {
				self.windowHeight( 0 );
			};

			return ( self.windowHeight() - padding ) + 'px';
        });
		self.moduleId = dnn.getVar('fiddleModId') || 0;
		self.baseUrl = dnn.getVar('baseUrl');

		self.contentViewModel = ko.mapping.fromJS(options.contentViewModel, mapping);

		self.pageRenderViewModel = new pageRenderViewModel();
		self.htmlPaneViewModel = new codeEditorViewModel("text/html");
		self.jsPaneViewModel = new codeEditorViewModel("javascript");
		self.cssPaneViewModel = new codeEditorViewModel("css");
		self.currentPane = self.htmlPaneViewModel;

	    /* Event Methods */
		self.setPage = function (data) {
		    self.currentPane = data;
		}

		self.renderPage = function (data, event) {
			var contentModel = self.contentViewModel,
				style = contentModel.css() ? '<style>' + contentModel.css() + '</style>\n' : "",
				body = contentModel.html() ? contentModel.html() + "\n" : "",
				bodyScript = contentModel.script() ? contentModel.script() : "",
				headScripts = "";

			$.each( contentModel.scripts(), function ( index, value ) {
			    if (value.enabled()) {
					headScripts += '<script type=\"text/javascript\" src=\"' + value.url().replace('~', self.baseUrl) + '\" ></script>\n';
				}
			} );

			self.pageRenderViewModel.render( style + headScripts, body, bodyScript );

			return true;
		};

		self.updateSettingsVisibility = function (data, event) {
			self.showSettings( !self.showSettings() );
		};

		self.save = function (appVM) {
			var fiddleDTO = ko.toJS( appVM.contentViewModel );
			fiddleDTO.moduleId = self.moduleId;
			delete fiddleDTO.scriptsViewModel;

			fiddleDTO = { "fiddleJSON": ko.toJSON(fiddleDTO) };

			$.ajax({
				type: "POST",
				beforeSend: fiddleService.ServicesFramework.setModuleHeaders,
				url: baseServicepath + "Save",
				data: fiddleService.ServicesFramework.getAntiForgeryProperty(fiddleDTO),
				dataType: "json"
            })
            .done(function () {
                document.location = $('#contentEditor .dnnActions a.dnnSecondaryAction').attr('href');
            });
		};

	    /* Initialization */
		self.Initialize = function() {
		    $(window).resize(function () { self.windowHeight($(window).height()); });
		    $.ajax({
		        type: "GET",
		        beforeSend: fiddleService.ServicesFramework.setModuleHeaders,
		        url: baseServicepath + "Get",
		        data: {moduleId: self.moduleId},
            })
            .done(function (data) {
                ko.mapping.fromJS(data, mapping, self.contentViewModel);
            })
            .fail(function () { });

		};

		self.Initialize();

	}

	var defaults = {
	    previewFrame: $('iframe#preview'),
	    contentViewModel: {
	        html: '',
	        css: '',
	        script: '',
	        scripts: [
			{
			    scriptid: 0,
			    name: 'jQuery',
			    url: '~/Resources/Shared/scripts/jquery/jquery.min.js',
			    enabled: true,
			    order: -3,
			    canDelete: false
			},
	        {
	            scriptid: 0,
	            name: 'jQuery UI',
	            url: '~/Resources/Shared/scripts/jquery/jquery-ui.min.js',
	            enabled: true,
	            order: -2,
	            canDelete: false
	        },
	        {
	            scriptid: 0,
	            name: 'KnockoutJS',
	            url: '~/desktopmodules/dnnfiddle/scripts/knockout-2.1.0.js',
	            enabled: true,
	            order: -1,
	            canDelete: false
	        }]
	    }
	}
	var appModel = new appViewModel(defaults);
	ko.applyBindings( appModel );

	$('#dnnFiddle').dnnTabs({ selected: 0 });
	$('#contentSettings').dnnTabs({ selected: 0 });

	$('#dnnFiddle').bind('tabsshow', function (event, ui) {
	    if (appModel.currentPane) appModel.currentPane.refresh.call(this);
	})

});

